-- USB串口功能测试
-- 2021.05.08
-- Lingd
-- 福州泰诚网络科技有限公司

module(...,package.seeall)

require"utils"
require"pm"
require "tool"
require "nvm"
require "handle"
require "net"
require "metering"
require "k24c02"
require "usart"

local UART_ID,rdbuf = uart.USB, ""

-- JSON协议解析
local function ptl_unpack(data)

	local tjsondata,result,errinfo = json.decode(data)
	if result and tjsondata["Cmd"] ~= nil then
		print(tjsondata["Cmd"])

		if tjsondata["Cmd"] == "GetCs" then					-- 获取配置信息
			local s_json = 
			{
				Cmd = tjsondata["Cmd"],
				CsCfg = 
				{	
					Fcdl =  nvm.get("MeuFI"),              	-- 浮充电流（A）
					Fcsj =  nvm.get("MeuFTime"),           	-- 浮充时间（s）
					Kzdl =  nvm.get("MeuMinI"),            	-- 最小电流（A）
					Kzsj =  nvm.get("MeuKTime"),           	-- 空载时间（s） 
					Zddl =  nvm.get("MeuMaxI"),            	-- 最大电流（A）
					Zddy =  nvm.get("MeuMaxU"),            	-- 最大电压（V）
					Zxdy =  nvm.get("MeuMinU"),            	-- 最小电压（V）
					Cdsj =  nvm.get("RmbTime"),            	-- 1元的充电时间（s）
					Bhsj =  nvm.get("MeuBTime"),           	-- 异常保护时间（s）
					Bhcs =  nvm.get("MeuBNum")             	-- 异常保护次数 	
				}
			}
			write(json.encode(s_json))
		elseif tjsondata["Cmd"] == "SetCs" or tjsondata["Cmd"] == "RstCs"  then		-- 恢复出厂设置
			if tjsondata["CsCfg"] ~= nil then
				nvm.set("MeuFI",tonumber(tjsondata["CsCfg"]["Fcdl"]))
				nvm.set("MeuFTime",tonumber(tjsondata["CsCfg"]["Fcsj"]))
				nvm.set("MeuMinI",tonumber(tjsondata["CsCfg"]["Kzdl"]))
				nvm.set("MeuKTime",tonumber(tjsondata["CsCfg"]["Kzsj"]))
				nvm.set("MeuMaxI",tonumber(tjsondata["CsCfg"]["Zddl"]))
				nvm.set("MeuMaxU",tonumber(tjsondata["CsCfg"]["Zddy"]))
				nvm.set("MeuMinU",tonumber(tjsondata["CsCfg"]["Zxdy"]))
				nvm.set("RmbTime",tonumber(tjsondata["CsCfg"]["Cdsj"]))
				nvm.set("MeuBTime",tonumber(tjsondata["CsCfg"]["Bhsj"]))
				nvm.set("MeuBNum",tonumber(tjsondata["CsCfg"]["Bhcs"]))
				
				handle.getcfg()								-- 重新获取配置
			end
			local s_json = {Cmd = tjsondata["Cmd"]}
			write(json.encode(s_json))
		elseif tjsondata["Cmd"] == "GetSysMsg" then			-- 获取系统信息
			local s_json = 
			{
				Cmd = tjsondata["Cmd"],
				CsCfg = 
				{	
					State 	=  net.getState(),
					Csq 	=  net.getRssi(),
					HeadVer =  "V1.0",
					SoftVer =  "V".._G.VERSION,
					CoreVer =  rtos.get_version()
				}
			}
			write(json.encode(s_json))
		elseif tjsondata["Cmd"] == "GetChargeMsg" then		-- 获取充电信息
			local s_json = 
			{
				Cmd = tjsondata["Cmd"],
				CsCfg = 
				{	
					Ch1 = {
						U = string.format("%3.2f",metering.Urms),
						I = string.format("%2.3f",metering.Irms[1]),
						Cdsj = handle.CdTime[1],
						Fcsj = handle.FbTime[1],
						Kzsj = handle.KbTime[1],
						Bhsj = handle.IbTime[1],
					},
					Ch2 = {
						U = string.format("%3.2f",metering.Urms),
						I = string.format("%2.3f",metering.Irms[2]),
						Cdsj = handle.CdTime[2],
						Fcsj = handle.FbTime[2],
						Kzsj = handle.KbTime[2],
						Bhsj = handle.IbTime[2],
					},
					Ch3 = {
						U = string.format("%3.2f",metering.Urms),
						I = string.format("%2.3f",metering.Irms[3]),
						Cdsj = handle.CdTime[3],
						Fcsj = handle.FbTime[3],
						Kzsj = handle.KbTime[3],
						Bhsj = handle.IbTime[3],
					},
					Ch4 = {
						U = string.format("%3.2f",metering.Urms),
						I = string.format("%2.3f",metering.Irms[4]),
						Cdsj = handle.CdTime[4],
						Fcsj = handle.FbTime[4],
						Kzsj = handle.KbTime[4],
						Bhsj = handle.IbTime[4],
					},
					Ch5 = {
						U = string.format("%3.2f",metering.Urms),
						I = string.format("%2.3f",metering.Irms[5]),
						Cdsj = handle.CdTime[5],
						Fcsj = handle.FbTime[5],
						Kzsj = handle.KbTime[5],
						Bhsj = handle.IbTime[5],
					},
					Ch6 = {
						U = string.format("%3.2f",metering.Urms),
						I = string.format("%2.3f",metering.Irms[6]),
						Cdsj = handle.CdTime[6],
						Fcsj = handle.FbTime[6],
						Kzsj = handle.KbTime[6],
						Bhsj = handle.IbTime[6],
					},
					Ch7 = {
						U = string.format("%3.2f",metering.Urms),
						I = string.format("%2.3f",metering.Irms[7]),
						Cdsj = handle.CdTime[7],
						Fcsj = handle.FbTime[7],
						Kzsj = handle.KbTime[7],
						Bhsj = handle.IbTime[7],
					},
					Ch8 = {
						U = string.format("%3.2f",metering.Urms),
						I = string.format("%2.3f",metering.Irms[8]),
						Cdsj = handle.CdTime[8],
						Fcsj = handle.FbTime[8],
						Kzsj = handle.KbTime[8],
						Bhsj = handle.IbTime[8],
					}
				}
			}
			write(json.encode(s_json))
			elseif tjsondata["Cmd"] == "SetCharge" then			
				if tjsondata["CsCfg"]["SetCh"] ~= nil then
				local ch = tonumber(tjsondata["CsCfg"]["SetCh"])
				log.info("ch",ch)
				if ch <= 8 then						-- 开启充电（不回复）
					handle.start_charge(ch,14400)	
				elseif ch == 9 then					-- 全部开启充电（不回复）
					handle.start_charge(1,14400)
					handle.start_charge(2,14400)
					handle.start_charge(3,14400)
					handle.start_charge(4,14400)
					handle.start_charge(5,14400)
					handle.start_charge(6,14400)
					handle.start_charge(7,14400)
					handle.start_charge(8,14400)
				elseif ch <= 18 then				-- 关闭充电（不回复）
					handle.end_charge(ch-10)
				elseif ch == 19 then				-- 全部关闭充电（不回复）
					handle.end_charge(1)
					handle.end_charge(2)
					handle.end_charge(3)
					handle.end_charge(4)
					handle.end_charge(5)
					handle.end_charge(6)
					handle.end_charge(7)
					handle.end_charge(8)
				end
			end
		elseif tjsondata["Cmd"] == "SetCaliU" then			-- 设置电压校准值	
		
			local U_data = metering.CalcCaliU(tonumber(tjsondata["Val"]))
			k24c02.WriteBytes(0x00,U_data)					-- 存入EEPROM
			metering.pack(metering.ID_1,metering.REG_UC,metering.RA,U_data)
			
		elseif tjsondata["Cmd"] == "SetCaliI" then			-- 设置电流校准值
		
			local Id = {metering.ID_1,metering.ID_1,metering.ID_2,metering.ID_2,metering.ID_3,metering.ID_3,metering.ID_4,metering.ID_4}
			local Reg = {metering.REG_IAC,metering.REG_IBC}
			local Ch = tonumber(tjsondata["Ch"])
			local I_data = metering.CalcCaliI(Ch,tonumber(tjsondata["Val"]))
			k24c02.WriteBytes(Ch*4,I_data)					-- 存入EEPROM
			metering.pack(Id[Ch],Reg[Ch%2+1],metering.WR,I_data)	
		
		elseif tjsondata["Cmd"] == "SetCaliAll" then		-- 设置全部校准值(先存入EEPROM，然后再统一配置)
			
			local Data,E_Data,i,j = {},{},1,1
			
			E_Data = metering.CalcCaliU(tonumber(tjsondata["U"]))
			Data[1] = E_Data[1]
			Data[2] = E_Data[2]
			Data[3] = E_Data[3]
			Data[4] = E_Data[4]
			
			for i = 1,8 do			
				E_Data = metering.CalcCaliI(i,tonumber(tjsondata["Ch"..i]))
				for j = 1,4 do				
					Data[i*4+j] = E_Data[j]
				end
			end

			k24c02.WriteBytes(0x04,Data)					-- 存入EEPROM
		
			usart.send_reglist()							-- 统一配置校准值
			
		elseif tjsondata["Cmd"] == "RstMcu" then			-- 复位计量芯片
			-- 复位后，立即配置系统寄存器
			metering.pack(metering.ID_1,metering.REG_SFTRST,metering.RA,{0xAF,0xBE,0x72,0x45})
			sys.timerStart(metering.pack,metering.SlotTime,metering.ID_1,metering.REG_SYSCTRL,metering.RA,{0x00,0x00,0x80,0x38})
		end
	else
		print("json.decode error",errinfo)
	end
end

-- 处理从USB串口读到的数据
local function proc(data)
    if not data or string.len(data) == 0 then return end
    -- 追加到缓冲区
    rdbuf = rdbuf..data    
	ptl_unpack(rdbuf)
    --log.info("usb","read",rdbuf)
    rdbuf = ""
end

-- 读取USB串口接收到的数据
local function read()
    local data = ""
    while true do        
        data = uart.read(UART_ID,"*l")
        if not data or string.len(data) == 0 then break end
        proc(data)
    end
end

-- 通过USB串口发送数据
function write(s)
    uart.write(UART_ID,s)
end

-- 初始化配置
pm.wake("usb")
uart.on(UART_ID,"receive",read)
uart.setup(UART_ID, 9600, 8, uart.PAR_ODD, uart.STOP_1)

local senddata = {0x7D,0x01,0xD4,0x01,0x00,0x00,0x00,0xDF}

--sys.timerLoopStart(write,1000,tool.HextoHexStr(senddata," "))
